import { join, relative } from 'path';
import { readdirSync, statSync } from 'fs';
import { Type } from '@nestjs/common';
import { PATH_METADATA } from '@nestjs/common/constants';

const ROUTE_PREFIX = '/admin'

// 递归获取所有控制器文件
function getControllerFiles(dir: string): string[] {
  const files = readdirSync(dir);
  const result: string[] = [];
  files.forEach((file) => {
    const fullPath = join(dir, file);
    if (statSync(fullPath).isDirectory()) {
      result.push(...getControllerFiles(fullPath));
    } else if (file.endsWith('.controller.js')) {
      result.push(fullPath);
    }
  });
  return result;
}

// 动态加载控制器并设置路由前缀
export function loadControllers(basePath: string, rootDir: string): Type<any>[] {
  const files = getControllerFiles(basePath);
  return files
    .map((file) => {
      const module = require(file); // 动态加载控制器模块
      const controllerClass = Object.values(module).find((m) => typeof m === 'function');
      if (controllerClass) {
        // 从文件路径生成路由前缀
        const relativePath = relative(rootDir, file)
          .replace(/\.controller\.js$/, '') // 去掉文件后缀
          .replace(/\\/g, '/') // 转换为 URL 路径格式
          .replace(/^controller\//, ''); // 去掉 controller 目录名

        const routePrefix = ROUTE_PREFIX + `/${relativePath}`;
        Reflect.defineMetadata(PATH_METADATA, routePrefix, controllerClass); // 动态设置路由前缀
        return controllerClass as Type<any>;
      }
      return null;
    })
    .filter((controller): controller is Type<any> => controller !== null); // 过滤空值
}
